#!/usr/bin/python
import cgi
import cgitb
import os
from pygallib import usersession
from pygallib import layoutlib
from pygallib import albumlib
from pygallib import userlib
from pygallib import picturelib

# Enable debug print
cgitb.enable()

logged_in = usersession.logged_in()
if logged_in:
  user = usersession.get_session_user()

headers = {}
headers["Content-type"] = "text/html"
layoutlib.print_http_headers(headers)
layoutlib.print_page_open("PyGallery - Home")
print("<body>")
menu = []
menu.append(("Home", "gallery.cgi"))

user = None
if logged_in:
  user = usersession.get_session_user()

layoutlib.print_page_header(menu, user)
print('<div id="page_body">')

# Get the fields from url
fields = cgi.FieldStorage()
form_errors = []
form_result = ""
if "password" in fields:
  new_user = {}
  for key in user.keys():
    new_user[key] = user[key]
  password = fields["password"].value
  password_confirm = fields["password_confirm"].value
  if len(password) > 0 and password == password_confirm:
    new_user["password"] = userlib.hash_password(password)
    try:
      userlib.update_user(new_user)
      form_result = "Account update successful."
    except Error:
      form_result = "Account update failed."
  else:
    form_errors.append("Passwords do not match")

if logged_in:
  for error in form_errors:
    print('<p>%s</p>' % error)
  if len(form_result) > 0:
    print('<p>%s</p>' % form_result)
  print("""
  <form method="post" action="account_settings.cgi">
    <ul>
      <li>
        <label for="password">Password:</label>
        <input type="password" name="password" value="" />
      </li>
      <li>
        <label for="password_confirm">Confirm password:</label>
        <input type="password" name="password_confirm" value="" />
      </li>
      <li>
        <input type="submit" value="Submit" />
      </li>
    </ul>
  </form>
  """)
else:
  print('<p>You need to <a href="login.cgi">login</a> first</p>')

print('</div>')
layoutlib.print_page_close()
